<template>
	<view class="container">
		<!-- 收货地址 -->
		<view class="address-card" @click="selectAddress">
			<view class="address-content" v-if="selectedAddress">
				<view class="address-icon">
					<uni-icons type="location-filled" size="24" color="#4cd964"></uni-icons>
				</view>
				<view class="address-info">
					<view class="address-header">
						<text class="name">{{ selectedAddress.contactName }}</text>
						<text class="separator">|</text>
						<text class="phone">{{ selectedAddress.contactPhone }}</text>
					</view>
					<view class="address-detail">
						{{ selectedAddress.address }}
					</view>
				</view>
			</view>
			<view class="address-empty" v-else>
				<uni-icons type="plus" size="20" color="#999"></uni-icons>
				<text>添加收货地址</text>
			</view>
			<uni-icons class="arrow-right" type="arrowright" size="20" color="#999"></uni-icons>
		</view>

		<!-- 商家信息 -->
		<view class="shop-info">
			<image class="shop-logo" :src="shopInfo.shopAvatar" mode="aspectFill"></image>
			<view class="shop-detail">
				<text class="shop-name">{{ shopInfo.shopName }}</text>
				<text class="shop-time" v-if="shopInfo.shopStart && shopInfo.shopEnd">
					{{ formatTime(shopInfo.shopStart) }} - {{ formatTime(shopInfo.shopEnd) }}
				</text>
			</view>
		</view>

		<!-- 订单商品列表 -->
		<view class="order-items">
			<view class="section-header">
				<text class="shop-name">{{ shopInfo.shopName }}</text>
				<text class="item-count">{{ selectedItems.length }}件商品</text>
			</view>

			<view class="item-list">
				<view class="item" v-for="item in selectedItems" :key="item.id">
					<!-- 添加商品图片 -->
					<image class="item-image" :src="getImageUrl(item.productImage)" mode="aspectFill"></image>
					<view class="item-info">
						<text class="item-name">{{ item.productName }}</text>
						<text class="item-spec" v-if="item.productDescription">{{ item.productDescription }}</text>
					</view>
					<view class="item-right">
						<text class="item-quantity">×{{ item.number }}</text>
						<text class="item-price">¥{{ item.productPrice.toFixed(2) }}</text>
					</view>
				</view>
			</view>
		</view>



		<!-- 订单备注 -->
		<view class="order-remark">
			<text class="label">备注</text>
			<input class="input" v-model="remark" placeholder="请输入备注信息(选填)" />
		</view>

		<!-- 订单金额明细 -->
		<view class="order-summary">
			<view class="summary-item">
				<text class="label">商品总价</text>
				<text class="value">¥{{ selectedItemsTotal.toFixed(2) }}</text>
			</view>
			<view class="summary-item">
				<text class="label">配送费</text>
				<text class="value">¥{{ deliveryFee.toFixed(2) }}</text>
			</view>
			<view class="summary-total">
				<text class="label">合计</text>
				<text class="value"> ¥{{ (selectedItemsTotal + deliveryFee).toFixed(2) }}</text>
			</view>
		</view>

		<!-- 提交订单按钮 -->
		<view class="submit-bar">
			<view class="total-price">
				<text>合计: ¥{{ (selectedItemsTotal + deliveryFee).toFixed(2) }}</text>
			</view>
			<button class="submit-btn" @click="createOrder" :disabled="!selectedAddress || selectedItems.length === 0">
				提交订单
			</button>
		</view>
	</view>
</template>


<script>
	import {
		createOrder
	} from '@/api/order/order';

	export default {
		data() {
			return {
				shopInfo: {},
				cart: {
					id: null,
					items: [],
					totalPrice: 0,
					totalQuantity: 0
				},
				selectedAddress: null,
				deliveryFee: 0,
				remark: '',
				orderNumber: '', // 新增订单号
				createTime: '', // 新增下单时间
				orderStatus: 0, // 新增订单状态
				selectedItems: [],
			};
		},
		computed: {
			selectedItemsTotal() {
				return this.selectedItems.reduce((sum, item) => sum + (item.productPrice * item.number), 0);
			}
		},
		async onLoad(options) {
			this.shopInfo.shopName = decodeURIComponent(options.shopName || '');
			this.cartId = options.cartId;
			this.shopId = options.shopId;
			this.deliveryFee = Number(options.deliveryFee) || 0;

			// 接收从商家页传递的选中商品
			const eventChannel = this.getOpenerEventChannel();
			eventChannel.on('acceptSelectedItems', (data) => {
				this.selectedItems = data.selectedItems;
			});

			this.generateOrderNumber();
			await this.loadShopInfo();
			await this.loadDefaultAddress();


			// 从Vuex获取地址
			this.updateAddressFromStore()



		},

		methods: {
			formatTime(timeString) {
				if (!timeString) return ''
				// 假设时间格式为 "HH:MM:SS" 或 "HH:MM"
				const parts = timeString.split(':')
				return `${parts[0]}:${parts[1]}` // 只显示小时和分钟
			},
			updateAddressFromStore() {
				const currentAddress = this.$store.getters['address/currentAddress']
				const currentLocation = this.$store.getters['address/currentLocation']

				if (currentAddress) {
					this.selectedAddress = currentAddress
				}
			},

			async loadDefaultAddress() {
				try {
					const customerId = this.$store.state.user.userData?.userId
					if (!customerId) return

					const res = await this.$api.address.getDefaultAddress(customerId)
					if (res.code === 200 && res.data) {
						await this.$store.dispatch('address/updateSelectedAddress', res.data)
						this.updateAddressFromStore()
					}
				} catch (error) {
					console.error('加载默认地址失败:', error)
				}
			},

			generateOrderNumber() {
				// 生成订单号: 日期+时间戳+随机数
				const date = new Date();
				const dateStr = date.getFullYear() +
					(date.getMonth() + 1).toString().padStart(2, '0') +
					date.getDate().toString().padStart(2, '0');
				const timestamp = date.getTime().toString().substr(-6);
				const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
				this.orderNumber = `ORDER${dateStr}${timestamp}${random}`;
				this.createTime = date.toISOString();
			},

			async loadShopInfo() {
				try {
					const res = await this.$api.shop.getShopDetail(this.shopId);
					if (res.code === 200) {
						this.shopInfo = {
							...res.data,
							shopAvatar: this.getImageUrl(res.data.shopAvatar)
						};
					}
				} catch (error) {
					console.error('加载店铺信息失败:', error);
					uni.showToast({
						title: '加载店铺信息失败',
						icon: 'none'
					});
				}
			},

			async loadCart() {
				try {
					const customerId = this.$store.state.user.userData?.userId;
					if (!customerId) {
						throw new Error('用户未登录');
					}

					const res = await this.$api.cart.getCartInfo(customerId, this.shopId);
					if (res.code === 200) {
						this.cart = {
							id: res.data.cartId,
							items: res.data.items || [],
							totalPrice: res.data.totalAmount || 0,
							totalQuantity: res.data.items.reduce((sum, item) => sum + item.number, 0)
						};
					}
				} catch (error) {
					console.error('加载购物车失败:', error);
					uni.showToast({
						title: '加载购物车失败',
						icon: 'none'
					});
				}
			},



			selectAddress() {
				uni.navigateTo({
					url: '/pages/user/address/list?selectMode=true'
				});
			},

			async createOrder() {
				// 1. 新增：校验用户是否登录（防止userId为空）
				const userId = this.$store.state.user.userData?.userId;
				if (!userId) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					// 跳转登录页（根据项目登录页路径调整）
					uni.navigateTo({
						url: '/pages/user/login'
					});
					return;
				}

				// 2. 原有：校验收货地址和选中商品
				if (!this.selectedAddress) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					});
					return;
				}
				if (this.selectedItems.length === 0) {
					uni.showToast({
						title: '请选择要购买的商品',
						icon: 'none'
					});
					return;
				}

				try {
					uni.showLoading({
						title: '创建订单中...'
					});

					// 3. 构造订单数据（与后端OrderCreateReqDTO完全匹配，无需修改）
					const orderData = {
						customerId: userId,
						businessId: this.shopId,
						cartId: this.cartId,
						// addressId: this.selectedAddress.id, // 删掉这行！！！
						deliveryFee: this.deliveryFee,
						remark: this.remark,
						orderNumber: this.orderNumber,
						orderItems: this.selectedItems.map(item => ({
							productId: item.productId,
							quantity: item.number,
							price: item.productPrice,
							productName: item.productName,
							productImage: item.productImage
						}))
					};

					// 4. 调用API创建订单（后端返回{code:200, data: 订单ID}）
					const res = await this.$api.order.createOrder(orderData); // 注意：这里要通过this.$api调用，而非直接import

					if (res.code === 200) {
						const orderId = res.data; // 后端返回的data就是订单ID（无需.res.data.orderId）
						const totalAmount = (this.selectedItemsTotal + this.deliveryFee).toFixed(2);

						// 5. 跳转到支付页面（传递订单ID和总金额）
						uni.navigateTo({
							url: `/pages/order/payment?orderId=${orderId}&totalAmount=${totalAmount}`
						});
					} else {
						uni.showToast({
							title: res.msg || '创建订单失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('创建订单失败:', error);
					uni.showToast({
						title: '创建订单失败，请重试',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			getImageUrl(imagePath) {
				if (!imagePath) return '/static/default-product.png';
				if (imagePath.startsWith('D:/')) {
					return imagePath.replace('D:/ruoyi/uploadPath', 'http://127.0.0.1:9300/uploadPath');
				}
				return imagePath;
			}

		},
		onShow() {
			this.updateAddressFromStore()
		}
	};
</script>

<style lang="scss">
	.container {
		padding-bottom: 120rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.address-card {
		background: linear-gradient(135deg, #f5f7fa 0%, #ffffff 100%);
		padding: 25rpx 30rpx;
		margin: 20rpx;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		border-left: 8rpx solid #4cd964;
		position: relative;
		overflow: hidden;

		&::before {
			content: "";
			position: absolute;
			top: 0;
			right: 0;
			width: 120rpx;
			height: 120rpx;
			background: rgba(76, 217, 100, 0.08);
			border-radius: 0 0 0 100%;
		}

		.address-content {
			flex: 1;
			display: flex;
			align-items: flex-start;

			.address-icon {
				margin-right: 20rpx;
				padding-top: 6rpx;
			}

			.address-info {
				flex: 1;

				.address-header {
					display: flex;
					align-items: center;
					margin-bottom: 12rpx;

					.name {
						font-size: 30rpx;
						font-weight: bold;
						color: #333;
					}

					.separator {
						margin: 0 12rpx;
						color: #ddd;
						font-size: 24rpx;
					}

					.phone {
						font-size: 26rpx;
						color: #666;
					}
				}

				.address-detail {
					font-size: 26rpx;
					color: #333;
					line-height: 1.5;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					overflow: hidden;
				}
			}
		}

		.address-empty {
			flex: 1;
			display: flex;
			align-items: center;
			color: #999;
			font-size: 28rpx;

			uni-icons {
				margin-right: 10rpx;
			}
		}

		.arrow-right {
			margin-left: 20rpx;
		}
	}

	.item-id {
		font-size: 22rpx;
		color: #999;
	}

	.item-list {
		.item {
			display: flex;
			justify-content: space-between;
			padding: 25rpx 0;
			border-bottom: 1rpx solid #f5f5f5;
			align-items: center; // 添加垂直居中

			&:last-child {
				border-bottom: none;
			}

			// 新增商品图片样式
			.item-image {
				width: 120rpx;
				height: 120rpx;
				border-radius: 8rpx;
				margin-right: 20rpx;
				background-color: #f5f5f5; // 默认背景色
			}

			.item-info {
				flex: 1;
				margin-right: 20rpx; // 为右侧留出空间

				.item-name {
					font-size: 26rpx;
					color: #333;
					margin-bottom: 8rpx;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					overflow: hidden;
				}

				.item-spec {
					font-size: 22rpx;
					color: #999;
				}
			}

			.item-right {
				display: flex;
				flex-direction: column;
				align-items: flex-end;

				.item-quantity {
					font-size: 24rpx;
					color: #666;
					margin-bottom: 8rpx;
				}

				.item-price {
					font-size: 26rpx;
					color: #f44;
					font-weight: bold;
				}
			}
		}
	}

	.address-card {
		background-color: #fff;
		padding: 30rpx;
		margin: 20rpx;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.address-content {
			flex: 1;
			margin-right: 20rpx;

			.address-header {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 10rpx;

				.name {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
				}

				.phone {
					font-size: 26rpx;
					color: #666;
				}
			}


		}

	}

	.shop-info {
		background-color: #fff;
		padding: 20rpx;
		margin: 0 20rpx 20rpx;
		border-radius: 12rpx;
		display: flex;
		align-items: center;

		.shop-logo {
			width: 80rpx;
			height: 80rpx;
			border-radius: 8rpx;
			margin-right: 20rpx;
		}

		.shop-detail {
			flex: 1;

			.shop-name {
				font-size: 28rpx;
				font-weight: bold;
				margin-bottom: 5rpx;
				display: block;
			}

			.shop-time {
				font-size: 24rpx;
				color: #666;
			}
		}
	}

	.order-items {
		background-color: #fff;
		margin: 20rpx;
		border-radius: 12rpx;
		padding: 0 20rpx;

		.section-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 25rpx 0;
			border-bottom: 1rpx solid #f5f5f5;

			.shop-name {
				font-size: 28rpx;
				font-weight: bold;
				color: #333;
			}

			.item-count {
				font-size: 24rpx;
				color: #999;
			}
		}


	}


	.order-remark {
		background-color: #fff;
		padding: 20rpx;
		margin: 0 20rpx 20rpx;
		border-radius: 12rpx;
		display: flex;
		align-items: center;

		.label {
			font-size: 28rpx;
			margin-right: 20rpx;
			color: #333;
		}

		.input {
			flex: 1;
			font-size: 26rpx;
			color: #666;
		}
	}

	.order-summary {
		background-color: #fff;
		padding: 20rpx;
		margin: 0 20rpx;
		border-radius: 12rpx;

		.summary-item {
			display: flex;
			justify-content: space-between;
			padding: 15rpx 0;

			.label {
				font-size: 26rpx;
				color: #666;
			}

			.value {
				font-size: 26rpx;
				color: #333;
			}
		}

		.summary-total {
			display: flex;
			justify-content: space-between;
			padding: 15rpx 0;
			border-top: 1rpx dashed #eee;
			margin-top: 10rpx;

			.label {
				font-size: 28rpx;
				font-weight: bold;
			}

			.value {
				font-size: 28rpx;
				font-weight: bold;
				color: #f44;
			}
		}
	}

	.submit-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 20rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);

		.total-price {
			font-size: 28rpx;
			font-weight: bold;
			color: #f44;
		}

		.submit-btn {
			width: 200rpx;
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background-color: #f44;
			color: #fff;
			border-radius: 40rpx;
			font-size: 28rpx;
			font-weight: bold;

			&[disabled] {
				background-color: #ccc;
			}
		}
	}
</style>